=<?php
/*
 * Copyright 2013 by Jerrick Hoang, Ivy Xing, Sam Roberts, James Cook, 
 * Johnny Coster, Judy Yang, Jackson Moniaga, Oliver Radwan, 
 * Maxwell Palmer, Nolan McNair, Taylor Talmage, and Allen Tucker. 
 * This program is part of RMH Homebase, which is free software.  It comes with 
 * absolutely no warranty. You can redistribute and/or modify it under the terms 
 * of the GNU General Public License as published by the Free Software Foundation
 * (see <http://www.gnu.org/licenses/ for more information).
 * 
 */

/*
 * 	addAppointment.php
 * 
 * 	@author Neil
 * 	@version 9/1/2008 revised 5/6/2014
 */
session_start();
session_cache_expire(30);
include_once('database/dbClinician.php');
include_once('domain/Clinician.php');
include_once('database/dbLog.php');
$id = str_replace("_"," ",$_GET["id"]);

if ($id == 'new') {
//    $clinician = new Client('new', 'applicant', null, null, null, null, null, null, null, null, null, null, null, null,
//                    null, null, "applicant", null, null, null, null, null, null, null, null, null, null, null, null, md5("new"));
                           
    $clinician = new Clinician($_POST['first_name'], $_POST['last_name'], $specialty, 
                                $_POST['phone1'], $_POST['phone2'], 
                                $_POST['ssn'],
                                $_POST['availability'],
                                $npi);
    
} else {
    //$clinician = retrieve_person($id);
    $clinician = retrieve_clinician($id);
    if (!$clinician) 
    { // try again by changing blanks to _ in id
        $id = str_replace(" ","_",$_GET["id"]);
        $clinician = retrieve_client($id);
        if (!$clinician) {
            echo('<p id="error">Error: there\'s no clinician with this id in the database</p>' . $id);
            die();
        }
    }
}
?>
<html>
    <head>
        <title>
            Appointments <?PHP echo($clinician->get_fname() . " " . $clinician->get_lname()); ?>
        </title>
        <link rel="stylesheet" href="styles.css" type="text/css" />
    </head>
    <body>
        <div id="container">
            <?PHP include('header.php'); ?>
            <div id="content">
                <?PHP
                include('clinicianValidate.inc');
                 $area = $_GET['area'];
                echo('<form method="post">');
                echo('<p><strong>Add Appointments:</strong>');
               
                echo '<p>Name (type a few letters): ';
                echo '<input type="text" name="s_name">';

                echo '<fieldset>
						<legend>Appointment Date: </legend>
							<table><tr>
								<td>Day (of week)</td>
								<td>Time Slot</td>
								</tr>';
                echo "<tr>";
                echo "<td>";
                $days = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');
                echo '<select name="s_day">' . '<option value=""></option>';
                foreach ($days as $day) {
                    echo '<option value="' . $day . '">' . $day . '</option>';
                }
                echo '</select>';
                echo "</td><td>";
                $shifts = array('morning' => 'Morning (9-12)', 'earlypm' => 'Early Afternoon (12-3)', 'latepm' => 'Late Afternoon (3-6)',
                    'evening' => 'Evening (6-9)', 'overnight' => 'Overnight');
                echo '<select name="s_shift">' . '<option value=""></option>';
                foreach ($shifts as $shiftno => $shiftname) {
                    echo '<option value="' . $shiftno . '">' . $shiftname . '</option>';
                }
                echo '</select>';
                echo "</td>";
                echo "</tr>";
                echo '</table></fieldset>';

                echo('<p><input type="hidden" name="s_submitted" value="1"><input type="submit" name="Search" value="Search">');
                echo('</form></p>');
                
                if ($_POST['_form_submit'] != 1)
                //in this case, the form has not been submitted, so show it
                    include('clinicianForm.inc');
                else {
                    //in this case, the form has been submitted, so validate it
                    $errors = validate_form();  //step one is validation.
                    // errors array lists problems on the form submitted
                    if ($errors) {
                        // display the errors and the form to fix
                        show_errors($errors);
                        if ($_POST['availability'] == null)
                            $ima = null;
                        else
                            $ima = implode(',', $_POST['availability']);
//                        $person = new Person($_POST['first_name'], $_POST['last_name'], $_POST['ssn'], $_POST['gender'],
//                                        $birthday,
//                                        $_POST['phone1'], $_POST['phone2'],
//                                        $_POST['status'],
//                                        $ima,
//                                        $specialty,
//                                        $availability,
//                                        $npi,
//                                        $clinicianID
//                                       //$_POST['medication_taken'], $_POST['admission_physical_notes'], $_POST['discharge_physical_notes'], $_POST['old_pass']
//                                       );
                        
                        $clinician = new Clinician($_POST['first_name'], $_POST['last_name'], $specialty, 
                                $_POST['phone1'], $_POST['phone2'], 
                                $_POST['ssn'],
                                $_POST['availability'],
                                $npi);
                        include('clinicianForm.inc'); // clinicianForm.inc needs to be written
                    }
                    // this was a successful form submission; update the database and exit
                    else
                        process_form($id);
                        echo "</div>";
                    include('footer.inc');
                    echo('</div></body></html>');
                    die();
                }

                /**
                 * process_form sanitizes data, concatenates needed data, and enters it all into a database
                 */
                function process_form($id) {
                    //echo($_POST['first_name']);
                    //step one: sanitize data by replacing HTML entities and escaping the ' character
                    $clinicianID = trim(str_replace('\\\'', '\'', htmlentities($_POST['clinicianID'])));// clinician ID
                    $first_name = trim(str_replace('\\\'', '', htmlentities(str_replace('&', 'and', $_POST['first_name']))));
                //    $first_name = str_replace(' ', '_', $first_name);
                    $last_name = trim(str_replace('\\\'', '\'', htmlentities($_POST['last_name'])));
                    $birthday = trim(str_replace('\\\'', '\'', htmlentities($_POST['birthday'])));
                    $specialty = trim(str_replace('\\\'', '\'', htmlentities($_POST['specialty']))); // added specialty 4/15
                    $availability = trim(str_replace('\\\'', '\'', htmlentities($_POST['availability']))); // added 4/15
                    $phone1 = trim(str_replace(' ', '', htmlentities($_POST['phone1'])));
                    $phone2 = trim(str_replace(' ', '', htmlentities($_POST['phone2'])));                 
                    $clean_phone1 = ereg_replace("[^0-9]", "", $phone1);
                    $clean_phone2 = ereg_replace("[^0-9]", "", $phone2);
                    $ssn = $_POST['ssn'];
               //   $gender = trim(htmlentities($_POST['gender']));
                    $npi = trim(str_replace(' ', '', htmlentities($_POST['npi'])));
                    $type = implode(',', $_POST['type']);
                    $screening_type = $_POST['screening_type'];
                    
//                    if ($screening_type!="") {
//                    	$screening = retrieve_dbApplicantScreenings($screening_type);
//                    	$step_array = $screening->get_steps();
//                    	$step_count = count($step_array);
//                    	$date_array = array();
//                    	for ($i = 0; $i < $step_count; $i++) {
//                        	$date_array[$i] = $_POST['ss_month'][$i] . '-' . $_POST['ss_day'][$i] . '-' . $_POST['ss_year'][$i];
//                        	if ($date_array[$i]!="--" && strlen($date_array[$i]) != 8) {
//                           	 	if (strlen($date_array[$i] != 2))
//                                	echo('<p>Date of completion for step: "' . $step_array[$i] . '" is in error, please select month, day <i>and</i> year.<br>');
//                            	$date_array[$i] = null;
//                        	}
//                    }
//                    $screening_status = implode(',', $date_array);
//                    }
                    
                    $status = $_POST['status'];
 
                    if ($_POST['availability'] != null)
                        $availability = implode(',', $_POST['availability']);
                    else
                        $availability = "";
                    // these two are not visible for editing, so they go in and out unchanged
                    $schedule = $_POST['schedule'];
                    //concatenate birthday and start_date strings
                    if ($_POST['DateOfBirth_Year'] == "")
                        $birthday = $_POST['DateOfBirth_Month'] . '-' . $_POST['DateOfBirth_Day'] . '-XX';
                    else
                        $birthday = $_POST['DateOfBirth_Month'] . '-' . $_POST['DateOfBirth_Day'] . '-' . $_POST['DateOfBirth_Year'];
                    if (strlen($birthday) < 8)
                        $birthday = '';
                    $start_date = $_POST['DateOfStart_Month'] . '-' . $_POST['DateOfStart_Day'] . '-' . $_POST['DateOfStart_Year'];
                    if (strlen($start_date) < 8)
                        $start_date = '';
                    $notes = trim(str_replace('\\\'', '\'', htmlentities($_POST['notes'])));
                    //used for url path in linking user back to edit form
                    $path = strrev(substr(strrev($_SERVER['SCRIPT_NAME']), strpos(strrev($_SERVER['SCRIPT_NAME']), '/')));
                    //step two: try to make the deletion, password change, addition, or change
                    if ($_POST['deleteMe'] == "DELETE") {
                        $result = retrieve_clinician($id);
                        if (!$result)
                            echo('<p>Unable to delete. ' . $first_name . ' ' . $last_name . ' is not in the database. <br>Please report this error to the House Manager.');
                        else {
                            //What if they're the last remaining manager account?
                            if (strpos($type, 'manager') !== false) {
                                //They're a manager, we need to check that they can be deleted
                                $managers = getall_type('manager');
                                if (!$managers || mysql_num_rows($managers) <= 1)
                                    echo('<p class="error">You cannot remove the last remaining manager from the database.</p>');
                                else {
                                    $result = remove_clinician($id);
                                    echo("<p>You have successfully removed " . $first_name . " " . $last_name . " from the database.</p>");
                                    if ($id == $_SESSION['_id']) {
                                        session_unset();
                                        session_destroy();
                                    }
                                }
                            } else {
                                $result = remove_clinician($id);
                                echo("<p>You have successfully removed " . $first_name . " " . $last_name . " from the database.</p>");
                                if ($id == $_SESSION['_id']) {
                                    session_unset();
                                    session_destroy();
                                }
                            }
                        }
                    }

                    // try to reset the clinician's password
                    else if ($_POST['reset_pass'] == "RESET") {
                        $id = $_POST['old_id'];
                        $result = remove_clinician($id);
                        $pass = $first_name . $clean_phone1;
                        
//                        $newclient = new Client($first_name, $last_name, $ssn, $gender, $birthday,
//                                            $phone1, $phone2, $status,
//                                            $medication_taken, $admission_physical_notes, $discharge_physical_notes,
//                                            md5($pass));
//                       $result = add_person($newclient);
                        
                        $newClinician = new Clinician($_POST['first_name'], $_POST['last_name'], $specialty, 
                                $_POST['phone1'], $_POST['phone2'], 
                                $_POST['ssn'],
                                $_POST['availability'],
                                $npi);
                        $result = add_clinician($newClinician);
                            
                        if (!$result)
                            echo ('<p class="error">Unable to reset ' . $first_name . ' ' . $last_name . "'s password.. <br>Please report this error to the House Manager.");
                        else
                            echo("<p>You have successfully reset " . $first_name . " " . $last_name . "'s password.</p>");
                    }

                    // try to add a new clinician to the database
                    else if ($_POST['old_id'] == 'new') {
                        $id = $first_name . $clean_phone1;
                        //check if there's already an entry.
                        $dup = retrieve_clinician($id);
                        if ($dup)
                            echo('<p class="error">Unable to add ' . $first_name . ' ' . $last_name . ' to the database. <br>Another clinician with the same name and phone is already there.');
                        else {
//                           $newclient = new Client($first_name, $last_name, $ssn, $gender, $birthday,
//                                            $phone1, $phone2, $status,
//                                           $medication_taken, $admission_physical_notes, $discharge_physical_notes,
//                                          md5($id));
//                         $result = add_person($newclient);
                            
                            // add new clinician to database
                            $newClinician = new Clinician($_POST['first_name'], $_POST['last_name'], $specialty, 
                                $_POST['phone1'], $_POST['phone2'], 
                                $_POST['ssn'],
                                $_POST['availability'],
                                $npi);
                            $result = add_clinician($newClinician);
                            
                            
                            if (!$result)
                                echo ('<p class="error">Unable to add " .$first_name." ".$last_name. " in the database. <br>Please report this error to the House Manager.');
//                            else if ($_SESSION['access_level'] == 0)
//                                echo("<p>Your application has been successfully submitted.<br>  The House Manager will contact you soon.  Thank you!");
                            else
                                echo("<p>You have successfully added " . $first_name . " " . $last_name . " to the database.</p>");
                        }
                    }

                    // try to replace an existing clinician in the database by removing and adding 
                    else {
                        $id = $_POST['old_id'];
                        $pass = $_POST['old_pass'];
                        $result = remove_clinician($id);
                        if (!$result)
                            echo ('<p class="error">Unable to update ' . $first_name . ' ' . $last_name . '. <br>Please report this error to the House Manager.');
                        else {
                            
//                            $newclient = new Client($first_name, $last_name, $ssn, $gender, $birthday,
//                                            $phone1, $phone2, $status,
//                                            $medication_taken, $admission_physical_notes, $discharge_physical_notes,
//                                            md5($pass));
//                           $result = add_person($newclient);
                            
                             $newClinician = new Clinician($_POST['first_name'], $_POST['last_name'], $specialty, 
                                $_POST['phone1'], $_POST['phone2'], 
                                $_POST['ssn'],
                                $_POST['availability'],
                                $npi);
                            $result = add_clinician($newClinician);
                            
                            if (!$result)
                                echo ('<p class="error">Unable to update ' . $first_name . ' ' . $last_name . '. <br>Please report this error to the House Manager.');
                            //else echo("<p>You have successfully edited " .$first_name." ".$last_name. " in the database.</p>");
                            else
                                echo('<p>You have successfully edited <a href="' . $path . 'clinicianEdit.php?id=' . $id . '"><b>' . $first_name . ' ' . $last_name . ' </b></a> in the database.</p>');
                            add_log_entry('<a href=\"clinicianEdit.php?id=' . $id . '\">' . $first_name . ' ' . $last_name . '</a>\'s Personnel Edit Form has been changed.');
                        }
                    }
                }
                ?>
            </div>
            <?PHP include('footer.inc'); ?>
        </div>
    </body>
</html> 
